﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Services;
using System.DirectoryServices;

namespace ADUserQuery
{
    class ADQueryClass : WebService
    {
        [WebMethod]
        public string ValidateActiveDirectoryLogin(/*string domain,*/ string username, string password)
        {
            Boolean success = false;
            string fullname = string.Empty;

            //DirectoryEntry Entry = new DirectoryEntry("LDAP://" + domain, username, password);
            DirectoryEntry Entry = new DirectoryEntry();
            Entry.Username = username;
            Entry.Password = password;
            DirectorySearcher searcher = new DirectorySearcher(Entry);
            searcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
            try
            {
                searcher.Filter = "(SAMAccountName=" + username + ")";
                //searcher.PropertiesToLoad
                searcher.PropertiesToLoad.Add("cn");
                System.DirectoryServices.SearchResult results = searcher.FindOne();

                #region OtherProp
                //var userFullName = results.GetDirectoryEntry().Properties["CN"].Value.ToString();
                //var a1 = results.GetDirectoryEntry().Properties["displayName"].Value.ToString();
                //var a2 = results.GetDirectoryEntry().Properties["name"].Value.ToString();
                //var a3 = results.GetDirectoryEntry().Properties["samAccountName"].Value.ToString(); 
                #endregion
                var first = results.GetDirectoryEntry().Properties["givenName"].Value.ToString();
                var last = results.GetDirectoryEntry().Properties["sn"].Value.ToString();

                success = (results != null);
                if (success)
                {
                    fullname = first + " " + last;

                }
            }
            catch (Exception)
            {
                success = false;
                //lblMessage.Text = "Error: " + ex.Message;
            }
            return fullname;
        }


    }
}
